package com.bdjk.bdmw.InfoGath.ws.push;



import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

import com.bdjk.bdmw.InfoGath.common.dao.impl.JdbcDAOImpl;
import com.bdjk.bdmw.InfoGath.exception.BusinessException;

public class BeiAnBeiPush extends JdbcDAOImpl {
	
	protected final Logger logger=Logger.getLogger(BeiAnBeiPush.class);
	private static final String appKey="34dc76b3d86680d7ff072cdf";
	private static final String masterSecret="09fb43cdc19d8a360e14ea92";
	
	
	public void pushLowBat(String ter_ident){
		
		try {
			List<String> register_ids=getRegisterId(ter_ident);
			String alert="low batterty! ";
			for(String registrationId:register_ids){
				sendPush(alert,registrationId);
			}
			
		} catch (BusinessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
	}
	
	public void sendPush(String alert,String registrationId){
		JPushClient jpushClient=new JPushClient(masterSecret,appKey,3);
		
		//String registrationId="1104a89792abf9ad476";
		PushPayload payload=pushByRegisId(alert,registrationId);
		
		try {
			PushResult result = jpushClient.sendPush(payload);
			logger.info("push result: "+result);
		} catch (APIConnectionException e) {
			// TODO Auto-generated catch block
			logger.error("Connection error. Should retry later. ",e);
		} catch (APIRequestException e) {
			// TODO Auto-generated catch block
			logger.error("Error response from JPush server. Should review and fix it.",e);
			logger.info("HTTP STATUS: "+e.getStatus());
			logger.info("ERROR CODE: "+e.getErrorCode());
			logger.info("ERROR MESSAGE: "+e.getErrorMessage());
			logger.info("Msg ID: "+e.getMsgId());
		}
		
	}
	
	
	public List<String> getRegisterId(String ter_ident) throws BusinessException{
		String sql="select registration_id from android_map where ter_ident=?";
		List<Object> params=new ArrayList<Object>();
		params.add(ter_ident);
		List<Object> resultSet=executeResultSQL(sql,params);
		List<String> register_ids=new ArrayList<String>();
		for(Object it:resultSet){
			register_ids.add((String)((List<Object>)it).get(0));
		}
		return register_ids;
	}
	
	
	public PushPayload pushByRegisId(String alert,String registrationId){
		return PushPayload.newBuilder()
				.setPlatform(Platform.android())
				.setAudience(Audience.registrationId(registrationId))
				.setNotification(Notification.alert(alert))
				.build();
	}

}
